import React, { useState, useRef } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Button, Table, Space, Form, Input, Popconfirm, Select } from "antd";
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  ExportOutlined,
  SearchOutlined,
  SyncOutlined,
  DownOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import TableLayout, {
  SearchContainer,
  SearchAction,
  SearchForm,
  OperateContainer,
  MainContainer,
} from "@/components/templates/TableLayout";
import { ButtonCollapsed } from "@/components/iteration";
import { DataEditorModel } from "@/pages/system/dict/components";
import { AuthButton } from "@/components/auth";
import { useLoadPageData } from "@/hooks";

import {
  getDictDataList,
  addDictData,
  updateDictData,
  deleteDictData,
  deleteBatchDictData,
} from "@/api/system/dict/data";
import PropTypes from "prop-types";

const AUTH_PERMISSION = {
  ADD: "system:dict:data:add",
  UPDATE: "system:dict:data:edit",
  DELETE: "system:dict:data:delete",
};

const HeaderComponent = ({ onSearch = () => {}, onReset }) => {
  const [folded, setFolded] = useState(false);
  const [searchType, setSearchType] = useState("keyword");
  const inputRef = useRef(null);

  const onFinish = (values) => {
    const data = Object.entries(values).filter(([_, value]) => !!value);
    data.length && onSearch(Object.fromEntries(data));
  };

  const hanldeSearch = () => {
    const value = inputRef.current.input.value;
    value && onSearch({ [searchType]: value });
  };

  const options = [
    { label: "综合搜索", value: "keyword", placeholder: "综合搜索" },
    { label: "字典标签", value: "dictLabel", placeholder: "请输入字典标签" },
    { label: "字典键值", value: "dictValue", placeholder: "请输入字典键值" },
  ];

  return (
    <SearchContainer>
      <SearchAction>
        <Space.Compact>
          <Select
            defaultValue={searchType}
            style={{ width: 120 }}
            options={options}
            onChange={(v) => setSearchType(v)}
          />
          <Input ref={inputRef} placeholder={options.find((item) => item.value === searchType).placeholder} />
          <Button icon={<SearchOutlined />} onClick={hanldeSearch} />
        </Space.Compact>

        <ButtonCollapsed
          type="link"
          icon={<DownOutlined />}
          iconPosition="end"
          collapsed={folded}
          onClick={() => setFolded(!folded)}
        >
          高级搜索
        </ButtonCollapsed>
      </SearchAction>

      <SearchForm collapse={folded}>
        <Form layout="inline" autoComplete="off" onFinish={onFinish} onReset={onReset}>
          <Form.Item name="dictLabel" label="字典标签">
            <Input placeholder="请输入字典标签" />
          </Form.Item>
          <Form.Item name="dictLabel" label="字典键值">
            <Input placeholder="请输入字典键值" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                搜索
              </Button>
              <Button icon={<SyncOutlined />} htmlType="reset">
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </SearchForm>
    </SearchContainer>
  );
};
HeaderComponent.propTypes = {
  onSearch: PropTypes.func,
  onReset: PropTypes.func,
};

const OperateCompoent = ({ deleteDisabled, onInsert, onBatchDelete, onRefresh }) => {
  const navigate = useNavigate();
  return (
    <OperateContainer>
      <Space>
        <AuthButton auth={AUTH_PERMISSION.ADD} type="primary" ghost icon={<PlusOutlined />} onClick={onInsert}>
          添加
        </AuthButton>

        <Popconfirm
          title="系统提示"
          description="是否确认删除多项用户的数据项？"
          onConfirm={() => onBatchDelete}
          okText="是"
          cancelText="否"
        >
          <AuthButton auth={AUTH_PERMISSION.DELETE} danger ghost icon={<DeleteOutlined />} disabled={deleteDisabled}>
            删除
          </AuthButton>
        </Popconfirm>
      </Space>
      <Space>
        <Button icon={<ReloadOutlined />} onClick={onRefresh} />
        <AuthButton auth={AUTH_PERMISSION.EXPORT} icon={<ExportOutlined />} onClick={() => navigate("export")} />
      </Space>
    </OperateContainer>
  );
};
OperateCompoent.propTypes = {
  deleteDisabled: PropTypes.bool,
  onInsert: PropTypes.func,
  onBatchDelete: PropTypes.func,
  onRefresh: PropTypes.func,
};

const TableComponent = ({ onEditor, onDelete, onChangeStatus, ...resProps }) => {
  const columns = [
    { key: "dictCode", title: "ID", dataIndex: "dictCode" },
    { key: "dictLabel", title: "字典标签", dataIndex: "dictLabel" },
    { key: "dictValue", title: "字典键值", dataIndex: "dictValue" },
    { key: "dictSort", title: "排序", dataIndex: "dictSort" },
    { key: "status", title: "状态", dataIndex: "status" },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space>
          <AuthButton
            auth={AUTH_PERMISSION.UPDATE}
            type="link"
            icon={<EditOutlined />}
            onClick={() => onEditor(record)}
          >
            编辑
          </AuthButton>

          <Popconfirm
            title="系统提示"
            description={`是否确认删除ID为${record.dictCode}的数据项？`}
            onConfirm={() => onDelete(record.dictCode)}
            okText="是"
            cancelText="否"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <MainContainer>
      <Table size="middle" {...resProps} columns={columns} />
    </MainContainer>
  );
};
TableComponent.propTypes = {
  onEditor: PropTypes.func,
  onDelete: PropTypes.func,
  onChangeStatus: PropTypes.func,
  resProps: PropTypes.object,
};

const GeneralComponent = () => {
  const { id: dictId } = useParams();

  const {
    loading,
    dataSource,
    pagination,
    onSearchData, // 搜索数据
    onRefreshData,
    onResetData,
    onPageChange,
  } = useLoadPageData(getDictDataList, { dictId });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [editorVisible, setEditorVisible] = useState(false);
  const [editorData, setEditorData] = useState({});
  const onAddData = async (values) => {
    values.dictId = dictId;
    await addDictData(values);
    onRefreshData();
  };

  const onEditorData = async (values) => {
    await updateDictData(values);
    onRefreshData();
  };

  const onDelete = async (value) => {
    await deleteDictData(value);
    onRefreshData();
    setSelectedRowKeys(selectedRowKeys.filter((item) => item !== value));
  };

  const onBatchDelete = async () => {
    if (!selectedRowKeys.length) return;
    await deleteBatchDictData(selectedRowKeys);
    onRefreshData();
    setSelectedRowKeys([]);
  };

  const onCancelModel = () => {
    Object.entries(editorData).length && setEditorData({});
    setEditorVisible(false);
  };

  return (
    <TableLayout>
      <DataEditorModel
        open={editorVisible}
        initialValues={editorData}
        onCallback={editorData.dictCode ? onEditorData : onAddData}
        onCancel={onCancelModel}
      />
      <HeaderComponent onSearch={onSearchData} onReset={onResetData} />
      <OperateCompoent
        onInsert={() => setEditorVisible(true)}
        isDeleteDisabled={!selectedRowKeys.length}
        onBatchDelete={onBatchDelete}
        onRefresh={onRefreshData}
      />
      <TableComponent
        dataSource={dataSource}
        loading={loading}
        rowSelection={{
          selectedRowKeys,
          getCheckboxProps: ({ admin }) => ({ disabled: admin }),
          onChange: (v) => setSelectedRowKeys(v),
        }}
        pagination={{
          current: pagination.pageNum,
          pageSize: pagination.pageSize,
          total: pagination.totalPages,
          showSizeChanger: true,
          showTotal: (total) => `共${total}条`,
          onChange: onPageChange,
        }}
        onEditor={(v) => {
          setEditorData(v);
          setEditorVisible(true);
        }}
        onDelete={onDelete}
      />
    </TableLayout>
  );
};

export default GeneralComponent;
